#!/bin/bash

### BEGIN INIT INFO
# Provides:		vlbistreamer
# Required-Start:	$remote_fs $syslog
# Required-Stop:	$remote_fs $syslog
# Default-Start:	2 3 4 5
# Default-Stop:      0 1 6
# Short-Description:	VLBI data streamering server
### END INIT INFO

# Author: Tomi Salminen <tlsalmin@gmail.com>

#Should be changed by install script on target bin
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin
DESC="Vlbistreamer packet streaming service"
NAME=vlbistreamer
PPRIORITY=no
#RTPRIO=20
NICENESS=-10
TIMEOUT=5
DEBVARS=/lib/init/vars.sh
DISTRO=OTHER

SCRIPTNAME=vbs_daemon
#scriptPath=${0%${SCRIPTNAME}}
#Daemon is usually in /etc/init.d so just running
#which 
scriptPath=$(which $SCRIPTNAME)
scriptPath=${scriptPath%$SCRIPTNAME}
#fi
source ${scriptPath}vbs_common_functions

DAEMON_ARGS=""
#PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/vbs_daemon

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

# Read configuration variable file if it is present
#[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# Load the VERBOSE setting and other rcS variables
if [ -f "$DEBVARS" ]
then
  . /lib/init/vars.sh
  DISTRO=DEBIAN
else
  VERBOSE=1
fi

#Doesnt work..
PPSTRING=""
if [ "$PPRIORITY" == "yes" ]
then
  PPSTRING=" -I real-time:4 "
fi


# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
if [ -f "$DEBVARS" ]
then
  . /lib/lsb/init-functions
  DISTRO=DEBIAN
fi

#Hack to get init script work on non-debian system
do_log()
{
  if [ "$DISTRO" == "DEBIAN" ]
  then
    log_end_msg $1
  else
    if [ "$1" == "0" ]
    then
      echo "OK"
    else
      echo "ERROR"
    fi
  fi
}
do_log_daemon()
{
  if [ "$DISTRO" == "DEBIAN" ]
  then
    log_daemon_msg $1 $2
  else
    echo "DAEMON" $1 $2
  fi
}
# Function that starts the daemon/service
#
do_hugepages()
{
  echo $(date --rfc-3339=seconds) "Checking if hugepages are in use.." | tee -a  $LOGFILE
  if [ "$(cat $CFGFILE |egrep -v "^#" |grep use_hugepage |cut -d' ' -f3)" == "1;" ] 
  then
    if [ "$(cat /proc/sys/vm/nr_hugepages)" == "0" ]
    then
      echo $(date --rfc-3339=seconds) "Initializing hugepages" | tee -a  $LOGFILE
      init_hugepages -c
    else
      echo $(date --rfc-3339=seconds) "Hugepages already initialized" | tee -a  $LOGFILE
    fi
  else
    echo "Hugepages not in use"
  fi
}
do_start()
{
  # Return
  #   0 if daemon has been started
  #   1 if daemon was already running
  #   2 if daemon could not be started
  if [ -n "$(ps -A | grep -v grep|grep -i vlbistreamer)" ] ; then
    echo "vlbistreamer already running"
    return 1;
  else
    do_hugepages
    #sudo -u $USER $BINDIR/vlbistreamer &>> $LOGFILE &
    #if [ -n "$(ps -A -o cmd | grep -v grep|grep -i $BINDIR/vlbistreamer)" ] ; then
    retval=-1
    if [ "$DISTRO" == "DEBIAN" ]
    then
      start-stop-daemon --start --make-pidfile --pidfile $PIDFILE -c ${USER}:{GROUP} --user ${USER} --group ${GROUP} --nicelevel $NICENESS --background --name $NAME ${PPSTRING} --quiet  --exec $DAEMON -- $DAEMON_ARGS
      retval=$?
    else
      #TODO: -g ${group} doesn't work for some reason
      sudo -u ${USER} $DAEMON &> $LOGFILE &
      retval=$?
      sudo renice -n $NICENESS $retval
      echo $! > $PIDFILE
    fi
    if [ "$retval" == 0 ]
    then
      #if [ "$PPRIORITY" == "yes" ]
      #then
	#TODO: This is not the correct way
	#sleep 1
	#chrt -f -p $RTPRIO  $(cat $PIDFILE) |tee -a $LOGFILE
      #fi
      #TODO: whats the right way to check if it started ok? 
      #TODO Doesn't work from service..
      echo $(date --rfc-3339=seconds) "Vlbistreamer started" | tee -a  $LOGFILE
      return 0
    else
      echo $(date --rfc-3339=seconds) "Error in vlbistreamer start" |tee -a  $LOGFILE
      return 2
    fi
  fi
}
do_stop()
{
  if [ -n "`ps -A -o cmd | grep -v grep|grep -i $DAEMON`" ] ; then
    #TODO: Proper pid stuff etc.
    #start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
    vbs_shutdown
    #sudo -u $USER $BINDIR/vbs_shutdown &>> $LOGFILE
    while [ -n "$(ps -A -o cmd | grep -v grep|grep -i $DAEMON)" -a "$TIMEOUT" -gt "0" ]
    do
      sleep 1
      TIMEOUT=$(($TIMEOUT-1))
    done
    #if start-stop-daemon --stop --pidfile $PIDFILE --name vlbistreamer --exec $BINDIR/vbs_logscript -- stop ; then
    if [ -z "$(ps -A -o cmd | grep -v grep|grep -i $DAEMON)" ] ; then
      echo $(date --rfc-3339=seconds) "Vlbistreamer stopped" | tee -a  $LOGFILE
      RETVAL=0
    else
      echo $(date --rfc-3339=seconds) "error in vlbistreamer stop" | tee -a  $LOGFILE
      RETVAL=2
    fi
  else
    echo "vlbistreamer not running"
    RETVAL=1
  fi
  rm -f $PIDFILE
  return "$RETVAL"
}
#
# Function that sends a SIGHUP to the daemon/service
#
do_reload() {
  #
  # If the daemon can reload its configuration without
  # restarting (for example, when it is sent a SIGHUP),
  # then implement that here.
  #
  #NOT IMPLEMENTED
  start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
  return 0
}

case "$1" in
  start)
    if [ "$DISTRO" == "DEBIAN" ]
    then
      [ "$VERBOSE" != no ] && do_log_daemon "Starting $DESC" "$NAME"
      do_start
      case "$?" in
	0|1) [ "$VERBOSE" != no ] && do_log 0 ;;
      2) [ "$VERBOSE" != no ] && do_log 1 ;;
    esac
  else
    echo "Not in debian so daemon start not logged"
    do_start
  fi
  ;;
stop)
  if [ "$DISTRO" == "DEBIAN" ]
  then
    [ "$VERBOSE" != no ] && do_log_daemon "Stopping $DESC" "$NAME"
    do_stop
    case "$?" in
      0|1) [ "$VERBOSE" != no ] && do_log 0 ;;
    2) [ "$VERBOSE" != no ] && do_log 1 ;;
  esac
else
  echo "Doing stop on non-debian machine"
  do_stop
  if [ "$?" == "0" ]
  then
    echo "Exit OK"
  else
    echo "Error in vlbistreamer stop"
  fi
fi
;;
status)
  status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
  ;;
#reload|force-reload)
  #
  # If do_reload() is not implemented then leave this commented out
  # and leave 'force-reload' as an alias for 'restart'.
  #
  #log_daemon_msg "Reloading $DESC" "$NAME"
  #do_reload
  #log_end_msg $?
  #;;
restart|force-reload)
  #
  # If the "reload" option is implemented then remove the
  # 'force-reload' alias
  #
  if [ "$DISTRO" == "DEBIAN" ]
  then
    do_log_daemon "Restarting $DESC" "$NAME"
  fi
  do_stop
  case "$?" in
    0|1)
      do_start
      if [ "$DISTRO" == "DEBIAN" ]
      then
	case "$?" in
	  0) do_log 0 ;;
	1) do_log 1 ;; # Old process is still running
      *) do_log 1 ;; # Failed to start
    esac
  fi
  ;;
*)
  # Failed to stop
do_log 1
  ;;
esac
;;
  *)
    #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
    echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
    exit 3
    ;;
esac

:

exit 0
